<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form small-top ">
        <div class="mainor_te">
          <!-- <el-button @click="exportb">导出明细</el-button>
          <el-button @click="exportb">导出汇总</el-button> -->
        </div>
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="90px"
          id="form"
        >
          <el-form-item label="配送日期：" prop="send_time">
            <el-date-picker
              v-model="form.send_time"
              type="date"
              class="wid220"
              :editable="false"
              placeholder="选择配送日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
              @change="getArticleList"
            />
          </el-form-item>
          <el-form-item label="商品分类：" prop="category_id" class="wid220">
            <el-cascader
              v-model="form.category_id"
              :options="options"
              :props="defaultProps"
              ref="cascaderHandle"
              collapse-tags
            ></el-cascader>
          </el-form-item>
          <el-form-item label="商品名称：" prop="goods_spu_id">
            <change-goods-input
              ref="changeGoodsInput"
              @clear="
                () => {
                  this.form.goods_spu_id = '';
                }
              "
              @sendValue="
                (data) => {
                  this.form.goods_spu_id = data.id;
                }
              "
            ></change-goods-input>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
          </MainFormBtn>
          <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, 'el-icon-arrow-down']"></i>
          </div>
          <div class="clearfix"></div>
          <el-collapse-transition>
            <div v-show="moredata">
              <div>
                <el-form-item label="配送时间：" prop="send_time_id">
                  <el-select
                    v-model.trim="form.send_time_id"
                    placeholder="配送时间"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(send_time_list, index) in list.send_time_list"
                      :key="index"
                      :label="send_time_list"
                      :value="parseInt(index)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="下单时间：" prop="order_time">
                  <el-select
                    v-model.trim="order_time_day"
                    placeholder="配送时间"
                    class="wid220"
                    @change="getArticleList"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(send_time_list, index) in created_time"
                      :key="index"
                      :value="send_time_list"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="order_time_day">
                  <el-time-picker
                    is-range
                    v-model="order_time"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    placeholder="选择时间范围"
                    @change="changeOrderTime"
                    value-format="HH:mm:ss"
                    default-value=""
                    class="width_310"
                  >
                  </el-time-picker>
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                  </MainFormBtn>
                </el-form-item>
              </div>
            </div>
          </el-collapse-transition>
        </el-form>
      </div>
      <div class="main-controls-wrap">
        <div>
          <el-button @click="batchSetting">
            采购方式
            <el-tooltip el-tooltip class="item" effect="dark" placement="bottom">
              <div slot="content">注释：可临时批量修改商品的采购方式！</div>
              <svg
                aria-hidden="true"
                class="navbar_svg new_navbar_svg"
                width="14"
                height="14"
              >
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
          </el-button>
          <el-button @click="generateClick" :loading="generateLoading">生成采购单</el-button>
        </div>
      </div>
      <div class="main_num boxdq mg-b-10">
        <div class="main_num_l box">
          <p>
            <em
              >1.商品生成了采购单后不会再出现在列表；2.库存充足的商品自动完成；3.配送中订单（含已完成）预定量、使用库存、在途库存等不会再汇总计算</em
            >
          </p>
        </div>
        <div class="mainsu_te" style="position: relative">
          <el-checkbox
            v-model="low_stocks"
            @change="
              (val) => {
                checkboxChange(val, 'low_stocks');
              }
            "
            >库存不足</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：勾选后，仅展示库存不足的商品</div>
            <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-checkbox
            v-model="usable_stock"
            @change="
              (val) => {
                checkboxChange(val, 'usable_stock');
              }
            "
            >使用库存</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：采购量=预定量-(库存-使用库存)</div>
            <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-checkbox
            v-model="road_stock"
            @change="
              (val) => {
                checkboxChange(val, 'road_stock');
              }
            "
            >在途库存</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：采购量=预定量-库存量-在途库存</div>
            <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
          <el-checkbox
            v-model="calculate_losses"
            @change="
              (val) => {
                checkboxChange(val, 'calculate_losses');
              }
            "
            >计算损耗</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">注释：采购量=预定量+（预定量*损耗率)</div>
            <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>

          <el-checkbox
            v-model="auto_merge_purchase"
            @change="
              (val) => {
                checkboxChange(val, 'auto_merge_purchase');
              }
            "
            >自动合并</el-checkbox
          >
          <el-tooltip class="item" effect="dark" placement="bottom">
            <div slot="content">
              注释：存在相同采购日期、采购方式、采购人员、采购类型、仓库，且状态为待采购的采购单
            </div>
            <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
              <use xlink:href="#icon-summary_question" />
            </svg>
          </el-tooltip>
        </div>
      </div>
      <div class="main_table">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          :row-class-name="getRowClass"
          :header-cell-class-name="this.$verticaline"
          :height="borderHeight"
          :row-key="getRowKeys"
          :expand-row-keys="expandRows"
          @expand-change="handleExpandChange"
          :header-cell-style="tableHeightStyle"
          @header-dragend="changeTableWidth"
          @row-click="rowDblclick"
        >
        <el-table-column type="expand" class-name="main_hei">
          <template slot-scope="props">
            <el-table
              :ref="'expandchild' + props.$index"
              :data="props.row.order_list"
              class="mainex_ta"
              fit
              :row-class-name="getExpandRowClass"
              :highlight-current-row="false"
              :key="props.row.goods_id"
            >
              <el-table-column width="90" align="right">
                <template slot-scope="scope">
                  <el-checkbox
                    v-model="scope.row.checked"
                    @change="(val) => twoChange(val, scope.row, props.$index)"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column label="订单号" prop="order_sn" width="200" />
              <el-table-column label="用户名称" width="200" prop="nickname">
                <template slot-scope="scope">
                  {{ scope.row.nickname
                  }}<span v-if="scope.row.zid_name"
                    >【{{ scope.row.zid_name }}】</span
                  >
                </template>
              </el-table-column>

              <el-table-column
                label="采购方式"
                prop="name"
                width="320"
                class-name="main_hei"
              >
                <template slot-scope="scope">
                  <div class="box">
                    <el-select
                      v-model.trim="scope.row.type"
                      placeholder="采购方式"
                      class="wid120"
                      @change="typeChange(scope)"
                    >
                      <el-option
                        v-for="(type_list, index) in list.type_list"
                        :key="index"
                        :label="type_list"
                        :value="parseInt(index)"
                        :disabled="index == 3 && scope.row.order_type == 2"
                      ></el-option>
                    </el-select>
                    <el-select
                      v-model.trim="scope.row.buyer_id"
                      placeholder="采购员"
                      class="wid160 marginLeft10"
                      v-if="scope.row.type == 1"
                      filterable
                    >
                      <el-option
                        v-for="(buyer, index) in list.buyer"
                        :key="index"
                        :label="buyer"
                        :value="parseInt(index)"
                      ></el-option>
                    </el-select>
                    <el-select
                      v-model.trim="scope.row.supplier_id"
                      placeholder="供应商"
                      class="wid160 marginLeft10"
                      v-if="scope.row.type == 2"
                      filterable
                    >
                      <el-option
                        v-for="(supplier, index) in list.supplier"
                        :key="index"
                        :label="supplier"
                        :value="parseInt(index)"
                      ></el-option>
                    </el-select>
                    <el-select
                      v-model.trim="scope.row.supplier_id"
                      placeholder="直供用户"
                      class="wid160 marginLeft10"
                      v-if="scope.row.type == 3"
                      filterable
                    >
                      <el-option
                        v-for="(direct_supply, index) in list.direct_supply"
                        :key="index"
                        :label="direct_supply"
                        :value="parseInt(index)"
                      ></el-option>
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="预定量" width="120" prop="order_num" />
              <el-table-column
                label="损耗"
                prop="ullage"
                v-if="calculate_losses"
              >
                <template slot-scope="scope">{{ scope.row.ullage }}</template>
              </el-table-column>
              <el-table-column
                label="预定小计"
                width="100"
                prop="order_num"
                v-if="calculate_losses"
              >
                <template slot-scope="scope">
                  {{
                    (Ntotal = $toFixed(
                      Number(scope.row.order_num) + Number(scope.row.ullage)
                    ))
                  }}
                </template>
              </el-table-column>
              <el-table-column
                label="使用库存量"
                width="120"
                prop="use_inventory"
                v-if="usable_stock"
              />
              <el-table-column label="采购量" width="120">
                <template slot-scope="scope">
                  {{ scope.row.purchase_num }}
                </template>
              </el-table-column>
              <el-table-column label="备注" prop="remark" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column :render-header="renderheader" width="50" align="center">
          <template slot-scope="scope">
            <el-checkbox
              v-model="scope.row.checked"
              @change="(val) => oneChange(val, scope.row)"
            ></el-checkbox>
          </template>
        </el-table-column>
        <!-- <el-table-column type="selection" /> -->
        <el-table-column
          label="商品名称"
          prop="name"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'name']"
        />
        <el-table-column
          label="单位"
          prop="unit"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'unit']"
        />
        <el-table-column
          label="预定总量"
          prop="order_num"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'order_num']"
        />
        <el-table-column
          label="损耗量"
          prop="ullage"
          :show-overflow-tooltip="true"
          v-if="calculate_losses"
          :width="tableWidth[hash + 'ullage']"
        >
          <template slot-scope="scope">{{ scope.row.ullage }}</template>
        </el-table-column>
        <el-table-column
          label="预定合计"
          prop="total"
          v-if="calculate_losses"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'total']"
        >
          <template slot-scope="scope">
            {{
              (total = $toFixed(scope.row.order_num + Number(scope.row.ullage)))
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="库存量"
          prop="inventory"
          v-if="usable_stock"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'inventory']"
        />
        <!-- <el-table-column
						label="使用库存量"
						prop="use_inventory"
						v-if="usable_stock"
						:show-overflow-tooltip="true"
					/> -->
        <el-table-column
          label="在途库存量"
          prop="in_pass_num"
          v-if="road_stock"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'in_pass_num']"
        />
        <el-table-column
          label="采购量"
          prop="purchase_num"
          :show-overflow-tooltip="true"
          :width="tableWidth[hash + 'purchase_num']"
        >
          <template slot-scope="scope">
            {{ scope.row.purchase_num
            }}<span
              v-if="scope.row.purchase_num == 0"
              style="color: red; margin-left: 10px"
              >所选商品库存充足，无需采购</span
            >
          </template>
        </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 批量设置弹窗 -->
    <el-dialog
      title="批量设置采购员/供应商"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div class="dialog_box">
        <el-form
          :inline="true"
          :model="batch_form"
          class="demo-form-inline"
          ref="batch_form"
          label-width="70px"
          :rules="rules"
        >
          <el-form-item label="" prop="type">
            <el-select
              v-model.trim="batch_form.type"
              placeholder="采购方式"
              class="wid220"
              :rules="rules.type"
            >
              <el-option
                v-for="(item, index) in batch_type"
                :key="index"
                :label="item"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="id" :rules="rules.id">
            <el-select
              v-model.trim="batch_form.id"
              placeholder="请选择"
              class="wid220"
              filterable
            >
              <el-option
                v-for="(item, index) in batch_list"
                :key="index"
                :label="item"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button @click="handleConfirm(1)" :loading="generateLoading">保存并生成采购单</el-button>
        <el-button type="primary" @click="handleConfirm(2)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  orderList_plan,
  purchase_addPlan,
  orderList_planGoods,
} from "@/api/purchasing/purchasingPlanned";
import { apiUrl, objKeySort, Md5, packApi } from "@/utils/public";
import { recursion, category, parseTime, getyesterday } from "@/utils/index";
import { setting_company } from "@/api/currency";
import rules from "@/rules/purchasing/purchasingPlanned";

export default {
  mixins: [mixins],
  data() {
    return {
      rules,
      generateLoading: false,
      // 搜索
      form: {
        name: "",
        pid: "",
        category_id: [],
        send_time: parseTime(new Date(), "{y}-{m}-{d}"),
        send_time_id: null,
        group_id: null,
        order_time_at: "",
        order_time_down: "",
      },
      isExpand: false,
      // 下单日期
      order_time: ["00:00:00", "23:59:59"],
      order_time_day: "",

      low_stocks: false,
      usable_stock: false,
      road_stock: false, //在途库存
      calculate_losses: false,
      auto_merge_purchase: false,
      // 更多
      moredata: false,
      // 列表数据
      list: {
        list: [],
      },
      // 下单日期
      created_time: [],
      listLoading: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        // checkStrictly: true,
        multiple: true,
      },
      // 展开行选择
      expand_row: [],
      checkAll: true,

      // 批量设置
      dialogVisible: false,
      batch_form: {
        type: "",
        id: "",
      },
      batch_type: {},
      batch_list: {},
      batch_buyer: {},
      batch_supplier: {},
      batch_direct_supply: {},
      total: 0,
      Ntotal: 0,

      getRowKeys(row) {
        return row.goods_spu_id;
      },
      expandRows: [],
    };
  },
  watch: {
    "list.list": {
      handler(val) {
        let all_list = val;
        let alllength = 0;
        all_list.map((e) => {
          let order_list_length = 0;
          e.order_list.map((p) => {
            if (!p.checked) {
              order_list_length++;
            }
          });
          if (order_list_length == e.order_list.length) {
            e.checked = false;
          } else {
            e.checked = true;
          }
          if (e.checked) {
            alllength++;
          }
        });
        if (alllength == all_list.length) {
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      },
      immediate: true,
      deep: true,
    },
    "batch_form.type": {
      handler(val) {
        this.batch_form.id = "";
        if (val && val == 1) {
          this.batch_list = this.batch_buyer;
        } else if (val && val == 2) {
          this.batch_list = this.batch_supplier;
        } else if (val && val == 3) {
          this.batch_list = this.batch_direct_supply;
        }
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    rowDblclick(row) {
      this.$refs.multipleTable.toggleRowExpansion(row)
    },
    // 点击搜索时将搜索条件进行折叠
    getSearchFor() {
      this.getArticleList();
    },
    // 敲击回车键时的回调
    startGetting() {
      this.getArticleList();
    },
    // 展开改变触发函数,只展开一行
    handleExpandChange(row, expandRows) {
      let that = this;
      if (expandRows.length > 0) {
        that.expandRows = [];
        if (row) {
          that.expandRows.push(row.goods_spu_id);
        }
      } else {
        that.expandRows = [];
      }
    },
    // 选择全部
    changeAll(val) {
      this.checkAll = val;
      // 全选反选
      this.list.list.map((e) => {
        e.checked = val;
        e.order_list.map((p) => {
          p.checked = val;
        });
      });
    },
    // 一级选择
    oneChange(val, row) {
      row.order_list.map((e) => (e.checked = val));
    },
    // 二级选择
    twoChange(val, row, index) {
      let list = JSON.parse(JSON.stringify(this.list.list[index]));
      let ids = [];
      let pro_ids = [];
      let order_list_ids = [];
      let pro_list_ids = [];
      ids = list.order_list
        .filter((e) => !e.checked && e.order_type == 1)
        .map((e) => e.order_list_id);
      pro_ids = list.order_list
        .filter((e) => !e.checked && e.order_type == 2)
        .map((e) => e.order_list_id);
      order_list_ids = list.order_list
        .filter((e) => e.order_type == 1)
        .map((e) => e.order_list_id);
      pro_list_ids = list.order_list
        .filter((e) => e.order_type == 2)
        .map((e) => e.order_list_id);
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        {
          ids: JSON.stringify(ids),
          pro_ids: JSON.stringify(pro_ids),
          goods_id: list.goods_id,
          goods_spu_id: list.goods_spu_id,
          order_list_ids: JSON.stringify(order_list_ids),
          pro_list_ids: JSON.stringify(pro_list_ids),
        }
      );
      orderList_planGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.list.list[index].order_money = res.data.data.order_money;
          this.list.list[index].order_num = res.data.data.order_num;
          this.list.list[index].purchase_num = res.data.data.purchase_num;
          this.list.list[index].ullage =
            res.data.data.ullage != "0.00" ? res.data.data.ullage : "";
          this.list.list[index].use_inventory = res.data.data.use_inventory;
          res.data.data.order_list.map((e, ind) => {
            this.list.list[index].order_list[ind].purchase_num = e.purchase_num;
            this.list.list[index].order_list[ind].use_inventory =
              e.use_inventory;
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },

    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass(row) {
      row.row.index = row.rowIndex;
      if (row.row.order_list) {
        if (row.row.order_list.length === 0) {
          return "row-expand-cover";
        }
      }
    },
    // 展开表格的样式
    getExpandRowClass(row) {
      if (row.row.show_border) {
        return "expandRow";
      }
    },
    /* ----  最先的处理方法----开始  ---- */
    // 监听展开行
    expandChange(rows, row) {
      this.expand_row = row;
      if (rows.checked) {
        rows.order_list.forEach((chil) => {
          setTimeout(() => {
            if (chil.checked) {
              if (this.$refs["expandchild" + rows.index]) {
                this.$refs["expandchild" + rows.index].toggleRowSelection(
                  chil,
                  true
                );
              }
            }
          }, 50);
        });
      }
    },
    onTableSelectAll(rows, row) {
      if (rows.length) {
        this.expand_row.forEach((e) => {
          if (this.$refs["expandchild" + e.index]) {
            this.$refs["expandchild" + e.index].toggleRowSelection(e, true);
          }
        });
      } else {
        this.expand_row.forEach((e) => {
          if (this.$refs["expandchild" + e.index]) {
            this.$refs["expandchild" + e.index].clearSelection();
          }
        });
      }
    },
    // 监听一级是否勾选
    onTableSelect(rows, row) {
      row.checked = !row.checked;
      this.$nextTick(() => {
        if (row.checked) {
          row.order_list.forEach((m) => {
            if (this.$refs["expandchild" + row.index]) {
              this.$refs["expandchild" + row.index].toggleRowSelection(m, true);
            }
            // m.checked = true;
          });
        } else {
          row.order_list.forEach((i) => {
            if (this.$refs["expandchild" + row.index]) {
              this.$refs["expandchild" + row.index].clearSelection();
            }
            // i.checked = false;
          });
        }
      });
    },
    oneTableChange(selection) {
      if (selection.length == this.list.list.length) {
        this.list.list.map((e) => {
          e.order_list.map((a, index) => {
            if (this.$refs["expandchild" + index]) {
              this.$refs["expandchild" + index].toggleRowSelection(a, true);
            } else {
              a.checked = true;
            }
          });
        });
      } else if (selection.length == 0) {
        this.list.list.map((e) => {
          e.order_list.map((a, index) => {
            if (this.$refs["expandchild" + index]) {
              this.$refs["expandchild" + index].clearSelection();
            } else {
              a.checked = false;
            }
          });
        });
      }
    },
    // 监听二级是否勾选
    expandSelect(rows, row, index) {
      row.checked = !row.checked;
      let pchecked = false;

      if (rows.length != 0) {
        this.list.list[index].checked = true;
        pchecked = true;
        this.$refs.multipleTable.toggleRowSelection(
          this.list.list[index],
          true
        );
      } else {
        this.list.list[index].checked = false;
        pchecked = false;
        this.$refs.multipleTable.toggleRowSelection(
          this.list.list[index],
          false
        );
      }

      let list = JSON.parse(JSON.stringify(this.list.list[index]));
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        {
          ids: JSON.stringify(
            list.order_list
              .filter((e) => !e.checked)
              .map((e) => e.order_list_id)
          ),
          goods_id: list.goods_id,
          goods_spu_id: list.goods_spu_id,
          order_list_ids: JSON.stringify(
            list.order_list.map((e) => e.order_list_id)
          ),
        }
      );
      orderList_planGoods(data).then((res) => {
        if (res.errcode == 0) {
          this.list.list[index].order_money = res.data.data.order_money;
          this.list.list[index].order_num = res.data.data.order_num;
          this.list.list[index].purchase_num = res.data.data.purchase_num;
          this.list.list[index].ullage =
            res.data.data.ullage != "0.00" ? res.data.data.ullage : "";
          this.list.list[index].use_inventory = res.data.data.use_inventory;
          res.data.data.order_list.map((e, ind) => {
            this.list.list[index].order_list[ind].purchase_num = e.purchase_num;
            this.list.list[index].order_list[ind].use_inventory =
              e.use_inventory;
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    /* ----  最先的处理方法----结束  ---- */

    // 生成采购单
    async generateClick() {
      this.generateLoading = true;
      let list = this.list_data();
      // 将采购量为0的商品剔除
      let purchaseNumList = [];
      list.forEach((item) => {
        if (item.purchase_num != 0) {
          purchaseNumList.push(item);
        }
      });
      if (list.length == 0) {
        this.$message.error("请勾选商品或该商品库存充足");
        this.generateLoading = false;
        return;
      }
      if (purchaseNumList.length == 0) {
        this.$message.error("所选商品库存充足，无需采购");
        this.generateLoading = false;
        return;
      }
      let data = packApi({
        list: JSON.stringify(list),
        send_time: this.form.send_time,
      });
      if (list.length != 0) {
        await purchase_addPlan(data).then((res) => {
          if (res.errcode == 0) {
            this.$message.success("生成采购单成功");
            this.orderList_plan();
          } else {
            this.$message.error(res.errmsg);
            this.generateLoading = false;
          }
        });
      } else {
        this.$message.error("请勾选商品");
        this.generateLoading = false;
      }
    },
    // 搜索勾选
    checkboxChange(val, type) {
      if (type == "usable_stock" && val == false) {
        this.road_stock = false;
        this.checkboxChange(false, "road_stock");
      }
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { [type]: val ? 1 : 0 })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { [type]: val ? 1 : 0 }
      );
      setting_company(data).then((res) => {
        if (res.errcode == 0) {
          this.orderList_plan();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    renderheader(h, { column, $index }) {
      return h("el-checkbox", {
        // 表示属性
        attrs: {
          effect: "dark",
        },
        props: {
          value: this.checkAll,
        },
        on: {
          change: (val) => {
            this.changeAll(val);
          },
        },
      });
    },
    // 导出明细
    exportb() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      orderList_planw(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "导出成功",
            type: "success",
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 搜索
    getArticleList() {
      let form = JSON.parse(JSON.stringify(this.form));
      this.orderList_plan();
    },

    //重置
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.order_time = ["00:00:00", "23:59:59"];
      this.order_time_day = "";
      this.$refs["changeGoodsInput"].name = "";
      this.orderList_plan();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    orderList_plan() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      orderList_plan(data).then((res) => {
        this.listLoading = false;
        this.generateLoading = false;
        if (res.errcode == 0) {
          // console.log(res)
          this.options = recursion(res.data.categoryList, false);
          res.data.list.map((e, index) => {
            e.checked = true;
            e.order_list.map((p, pindex, arr) => {
              let buyer_isExit = false;
              let supplier_isExit = false;
              let direct_supply_isExit = false;
              if (p.type == 0) {
                p.type = "";
              }
              for (const key in res.data.buyer) {
                if (key == p.buyer_id) {
                  buyer_isExit = true;
                  break;
                }
              }
              for (const key in res.data.supplier) {
                if (key == p.supplier_id) {
                  supplier_isExit = true;
                  break;
                }
              }
              for (const key in res.data.direct_supply) {
                if (key == p.supplier_id) {
                  direct_supply_isExit = true;
                  break;
                }
              }
              if (p.buyer_id == 0) {
                p.buyer_id = null;
              } else {
                if (!buyer_isExit) {
                  p.buyer_id = null;
                }
              }

              if (!supplier_isExit && p.type == 2) {
                p.supplier_id = null;
              }
              if (!direct_supply_isExit && p.type == 3) {
                p.supplier_id = null;
              }
              p.checked = true;
              // 订单加工单分界
              p.show_border = false;
              if (
                p.order_type == 1 &&
                arr[pindex + 1] &&
                arr[pindex + 1].order_type == 2
              ) {
                p.show_border = true;
              }
            });
            this.$nextTick(() => {
              if (this.$refs["multipleTable"]) {
                this.$refs["multipleTable"].toggleRowSelection(e, true);
              }
            });
          });
          this.low_stocks = res.data.low_stocks == 1 ? true : false;
          this.usable_stock = res.data.usable_stock == 1 ? true : false;
          this.road_stock = res.data.road_stock == 1 ? true : false;
          this.calculate_losses = res.data.calculate_losses == 1 ? true : false;
          this.auto_merge_purchase =
            res.data.auto_merge_purchase == 1 ? true : false;
          this.list = res.data;
          if (res.data.created_time) {
            this.created_time = res.data.created_time;
          }
          this.batch_type = res.data.type_list;
          this.batch_buyer = res.data.buyer;
          this.batch_supplier = res.data.supplier;
          this.batch_direct_supply = res.data.direct_supply;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    handle(array) {
      let arr = [];
      array.map((e) => {
        arr.push(e[1]);
      });

      arr = JSON.stringify(arr);
      return arr;
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      // form.pid = form.category_id[0] ? form.category_id[0] : "";
      let array = JSON.parse(JSON.stringify(form.category_id));
      form.category_id = this.handle(array);
      if (this.order_time_day) {
        form.order_time_at = this.order_time_day + " " + this.order_time[0];
        form.order_time_down = this.order_time_day + " " + this.order_time[1];
      }else {
        this.form.order_time_at = ''
        this.form.order_time_down = ''
      }
      return form;
    },
    list_data() {
      let arry = [];
      let list = JSON.parse(JSON.stringify(this.list.list));
      list.map((e, index) => {
        if (e.checked && e.purchase_num != 0) {
          e.order_list.map((p) => {
            if (p.checked) {
              arry.push({
                goods_id: e.goods_id,
                goods_spu_id: e.goods_spu_id,
                unit: e.unit,
                goods_name: e.goods_name,
                spu_name: e.spu_name,
                order_list_id: p.order_type == 1 ? p.order_list_id : "",
                pro_list_id: p.order_type == 1 ? "" : p.order_list_id,
                use_inventory: p.use_inventory,
                type: p.type,
                purchase_num: p.purchase_num,
                order_num: p.order_num,
                ullage: p.ullage != "0.00" ? p.ullage : "",
                buyer_id: p.buyer_id == null ? 0 : p.buyer_id,
                supplier_id: p.supplier_id == null ? 0 : p.supplier_id,
                pid: e.pid,
                category_id: e.category_id,
                sort: e.sort,
              });
            }
          });
        }
      });
      return arry;
    },
    // 下单时间选择
    changeOrderTime(val) {
      if (val) {
        this.form.order_time_at = JSON.stringify(
          this.order_time_day + "" + val[0]
        );
        this.form.order_time_down = JSON.stringify(
          this.order_time_day + "" + val[1]
        );
      }
      this.getArticleList();
    },
    // 采购方式切换
    typeChange(scope) {
      scope.row.buyer_id = "";
      scope.row.supplier_id = "";
    },
    //批量设置
    batchSetting() {
      this.dialogVisible = true;
    },
    // 批量设置确认
    handleConfirm(state) {
      this.$refs["batch_form"].validate(async (valid) => {
        if (valid) {
          let id = Number(this.batch_form.id);
          let type = Number(this.batch_form.type);
          this.list.list.map((e) => {
            if (e.order_list.length > 0 && e.checked) {
              e.order_list.map((p) => {
                if (p.checked) {
                  p.type = type;
                  p.buyer_id = "";
                  p.supplier_id = "";
                  switch (p.type) {
                    case 1:
                      p.buyer_id = id;
                      break;
                    case 2:
                      p.supplier_id = id;
                      break;
                    case 3:
                      if (p.order_type == 1) {
                        p.supplier_id = id;
                      } else {
                        p.type = "";
                        p.supplier_id = "";
                      }
                      break;
                  }
                }
              });
            }
          });
          if(state === 1) {
            await this.generateClick();
          }
          this.dialogVisible = false;
          this.batch_form.type = "";
          this.batch_form.id = "";
        }
      });
    },
  },
  created() {
    // 列表
    this.getNumerical(180);
    this.orderList_plan();
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 280px);
  .width_310 {
    width: 310px;
  }
}
.dialog_box {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.new_navbar_svg {
  vertical-align: top;
}
.mainor_tea {
  height: 32px;
}

/deep/.main_table .el-table .el-table__body .expandRow > td {
  border-bottom: 2px dashed #67c23a !important;
}
/deep/.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
</style>
